//
//  YBNetHelper.swift
//  Moonlight
//
//  Created by 清风徐来 on 2024/3/11.
//  Copyright © 2024 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import CocoaAsyncSocket

class YBNetHelper: NSObject {
    private var callback: TelnetConnectionCallback?

    init(callback: TelnetConnectionCallback) {
        self.callback = callback
    }

    func checkPort(ip: String, port: UInt16) {
        let socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        socket.delegateQueue = DispatchQueue.main
        try? socket.connect(toHost: ip, onPort: port, withTimeout: 2)
    }

}


extension YBNetHelper: GCDAsyncSocketDelegate {

    func  socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        PPP("连接成功")
        callback?.onConnectionSuccess()
    }

    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        PPP("失去连接")
        callback?.onConnectionFailed(err.debugDescription)
    }

}

protocol TelnetConnectionCallback: AnyObject {
    func onConnectionSuccess()
    func onConnectionFailed(_ errorMessage: String)
}
